using System;
using System.Collections.Generic;
using System.Text;
using AppExtensions.Views;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;

namespace AppExtensions.Helpers
{
  public static class With
  {
    public delegate void WithLoginActionDelegate();

    public static void Login(IBaseView view, string sessionKey,
        object sessionObject, WithLoginActionDelegate action)
    {
      if (view == null)
        throw new ArgumentNullException("view");

      if (view.Session == null)
        throw new ArgumentException("view must have a valid Session object", "view");

      if(action == null)
        throw new ArgumentNullException("action");

      if (view.UserId == null)
      {
        // Save the sessionObject in the session, then redirect to get a valid login
        if (sessionKey != null)
          view.Session.Add(sessionKey, sessionObject);

        view.RedirectToLogin();
      }
      else
      {
        action.Invoke();
      }
    }

    public delegate void ActionDelegate();

    public static void TryCatch(string policyName, ActionDelegate action)
    {
      try
      {
        action();
      }
      catch (Exception ex)
      {
        bool rethrow = ExceptionPolicy.HandleException(ex, policyName);
        if (rethrow)
          throw;
      }
    }
  }
}
